
package com.yoosora.plugins;

import com.alibaba.fastjson.JSON;
import com.mikuac.shiro.annotation.MessageHandler;
import com.mikuac.shiro.common.utils.MsgUtils;
import com.mikuac.shiro.common.utils.RegexUtils;
import com.mikuac.shiro.core.Bot;
import com.mikuac.shiro.core.BotPlugin;
import com.mikuac.shiro.dto.event.message.WholeMessageEvent;
import com.yoosora.common.consts.ConstsS;
import com.yoosora.model.TarotDataBean;
import com.yoosora.model.TarotDataBean.Tarot;
import com.yoosora.utils.ApiConst;
import com.yoosora.utils.RegexConst;
import com.yoosora.utils.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.yaml.snakeyaml.Yaml;
import javax.annotation.PostConstruct;
import javax.validation.constraints.NotNull;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Random;


/**
 * @author yoosora
 */

@Slf4j
@Component
public class ImagePlugin extends BotPlugin {
	
	private static StringBuilder sb = new StringBuilder();
	
	@Value("${server.port}")
	private String port;
	
	private List<Tarot> tarot;
	
	
	@MessageHandler(cmd = RegexConst.THROW_USER)
	public void satoriMsg(@NotNull Bot bot, @NotNull WholeMessageEvent event){
		String msg = event.getMessage();
		String atId = RegexUtils.regexGroup(RegexConst.AT, msg, 1);
		if(null!=atId&& Strings.isNotEmpty(atId)&&!"all".equals(atId)){
			sb.append("http://localhost:").append(port).append("/satori?qq=").append(atId);
			bot.sendMsg(event, MsgUtils.builder().img(sb.toString()).build(),false );
		}
		sb.setLength(0);
	}
	
	@PostConstruct
	public void tarotInit() throws UnsupportedEncodingException {
		Yaml yaml = new Yaml();
		InputStream resource = this.getClass().getClassLoader().getResourceAsStream("tarot.yaml");
		BufferedReader br = new BufferedReader(new InputStreamReader(resource,"UTF-8"));
		Object load = yaml.load(br);
		TarotDataBean tarotDataBean = JSON.parseObject(JSON.toJSONString(load), TarotDataBean.class);
		tarot = tarotDataBean.getTarot();
		log.info("塔罗牌初始化成功!");
	}
	
	@MessageHandler(cmd = RegexConst.TAROT)
	public void tarotMsg(@NotNull Bot bot,@NotNull WholeMessageEvent event){
		int msgId = event.getMessageId();
		Random random = new Random();
		int card = random.nextInt(22);
		int position = random.nextInt(2);
		Tarot tarot = this.tarot.get(card);
		sb.append(tarot.getName()).append(ConstsS.RN)
				.append(position == 0?"[正位]":"[逆位]")
				.append(position == 0?tarot.getPositive():tarot.getNegative());
		bot.sendMsg(event, MsgUtils.builder().text(sb.toString())
				.img(ApiConst.YOOSORA_IMG +tarot.getImageName())
				.reply(msgId)
				.build(),false );
		sb.setLength(0);
	}
	
	
}

